08. Exercise: Add a Content Intent

L1 A08 Add A Content Intent

Android Developer Documentation

Exercise

  1. Open NotificationUtils.kt and find the sendNotification() extension function. First, you need to create an intent with your applicationContext and the activity to be launched.
// NotificationUtils.kt

fun NotificationManager.sendNotification(messageBody: String, applicationContext: Context) {
    // Create the content intent for the notification, which launches
    // this activity
   // TODO: Step 1.11 create intent
    val contentIntent = Intent(applicationContext, MainActivity::class.java)

Next, you need to create a new PendingIntent . The system will use the pending intent to open your app.

  1. Create a PendingIntent with applicationContext, notification id, the content intent you created in the previous step and the PendingIntent flag. The PendingIntent flag specifies the option to create a new PendingIntent or use an existing one. You need to set PendingIntent.FLAG_UPDATE_CURRENT as the flag since you don’t want to create a new notification but to update if there is an existing one. This way you will be modifying the current PendingIntent which is associated with the Intent you are supplying.
// NotificationUtils.kt
   // TODO: Step 1.12 create PendingIntent
    val contentPendingIntent = PendingIntent.getActivity(
        applicationContext, 
        NOTIFICATION_ID,
        contentIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
    )
  1. Next, pass the PendingIntent to your notification. You do this by calling setContentIntent() on the NotificationBuilder. Now when you click the notification, the PendingIntent will be triggered, opening up your MainActivity.




  1. Also set setAutoCancel() to true, so that when the user taps on the notification, the notification dismisses itself as it takes you to the app.
// NotificationUtils.kt

// Build the notification
val builder = NotificationCompat.Builder(applicationContext,
    applicationContext.getString(R.string.default_notification_channel_id)
)
    .setSmallIcon(R.drawable.cooked_egg)          
    .setContentTitle(applicationContext.getString(R.string.notification_title))
    .setContentText(messageBody)
    // TODO: Step 1.13 set content intent
    .setContentIntent(contentPendingIntent)
    .setAutoCancel(true)
  1. Now run the app again, set a timer, put the app in the background and wait for the notification to appear. Once you see the notification, click on the notification by pulling the status bar and observe how the app is brought to the foreground.